<template>
  <div class="table-page-search-wrapper">
    <a-card>
      <detail-list>
        <detail-list-item term="导师编号">{{ teacherInfo.gh }}</detail-list-item>
        <detail-list-item term="姓名">{{ teacherInfo.xm }}</detail-list-item>
        <detail-list-item term="性别">{{ teacherInfo.xbmc }}</detail-list-item>
        <detail-list-item term="出生日期">{{ teacherInfo.csrq && teacherInfo.csrq.format('YYYY-MM-DD') }}</detail-list-item>
        <detail-list-item term="导师类别">{{ teacherInfo.dslbmc }}</detail-list-item>
      </detail-list>
    </a-card>
    <a-card :bordered="false" style="margin-top: 10px">
      <div style="margin-bottom: 10px; font-weight: bold;">导师指导专业</div>
      <!-- <div style="margin-bottom: 10px; font-weight: bold;">导师指导专业<span style="color: #1890ff">（出生日期在({{ tutorMasterAdmissionAgeLine }})之前的导师无法进行硕士招生；({{ tutorDoctoralAdmissionAgeLine }})之前的导师无法进行博士招生）</span></div> -->
      <a-form :form="form" style="margin-bottom: 10px;">
        <a-row>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="招生单位" :labelCol="{span: 6,offset: 1}" :wrapperCol="{span: 16, offset: 1}">
              <a-select @change="yxChange" v-decorator="[
                    'zdzyssyxdm',
                    {
                      rules: [{ required: true, message: '请选择招生单位!' }],
                    }
                  ]" showSearch :filterOption="filterOption">
                <a-select-option v-for="i in selectMenu.yx" :key="i.id" :value="i.yxm">{{ i.yxm }} {{ i.dwmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="专业层次" :labelCol="{span: 8,offset: 1}" :wrapperCol="{span: 14, offset: 1}">
              <a-select @change="zyccChange" v-decorator="[
                    'zyccm',
                    {
                      rules: [{ required: true, message: '请选择专业层次!' }],
                    }
                  ]">
                <a-select-option v-for="(i,index) in TYPE0353" :key="index" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="指导专业" :labelCol="{span: 8,offset: 1}" :wrapperCol="{span: 14, offset: 1}">
              <a-select v-decorator="[
                    'zdzym',
                    {
                      rules: [{ required: true, message: '请选择指导专业!' }],
                    }
                  ]" showSearch :filterOption="filterOption">
                  <a-select-option v-for="i in selectMenu.zy" :key="i.id" :value="i.zyh">{{ i.zyh}} {{ i.zymc }}</a-select-option>
                </a-select>
            </a-form-item>
          </a-col>

          <a-col :lg="8" :md="12" :sm="24">
            <a-button type="primary" style="margin-left: 20px;" @click="addItem">添加</a-button>
            <a-button type="danger" style="margin-left: 20px;" @click="batchDelete">删除</a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        :columns="columns"
        :dataSource="dszdzyList"
        :rowSelection="rowSelection"
        size="middle"
        :pagination="false"
        :scroll="{ y: 240 }"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="zdzy" slot-scope="text, record">{{ record.zdzym }} {{ record.zdzymc }}</span>
      </a-table>
    </a-card>
    <a-card :bordered="false" style="margin-top: 10px">
      <div v-for="zy in dszdzyList" :key="zy.zdzym">
        <div class="research-title">
          {{ zy.zdzyssyxdmc }} --- {{ zy.zdzym }}{{ zy.zdzymc }}（{{ zy.zyccmc }}）的研究方向：
        </div>
        <div>
          <a-checkbox-group :disabled="currentUser.departmentId && zy.zdzyssyxdm !== currentUser.departmentId" :options="zy.researchList" v-model="zy.dsyjfxList" />
        </div>
      </div>
      <a-row style="text-align: center; margin-top: 20px">
        <a-button style="margin-right:20px" @click="back">返回</a-button>
        <a-button type="primary" :loadingBtn="loadingBtn" @click="save">确认保存</a-button>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import DetailList from '~/tool/DetailList'
import { mapState } from 'vuex'
const DetailListItem = DetailList.Item

export default {
  data () {
    return {
      teacherInfo: {},
      loadingBtn: false,
      dszdzyList: [],
      selectMenu: {},
      columns: [
        {
          title: '序号',
          width: 100,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '院系',
          dataIndex: 'zdzyssyxdmc'
        },
        {
          title: '指导专业',
          // dataIndex: 'zymc',
          scopedSlots: { customRender: 'zdzy' }
        },
        {
          title: '专业层次',
          width: 100,
          dataIndex: 'zyccmc'
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      tutorMasterAdmissionAgeLine: '',
      tutorDoctoralAdmissionAgeLine: ''
    }
  },
  computed: {
    ...mapState({
      // systemInfo: state => state.app.systemInfo,
      currentUser: state => state.account.user,
      TYPE0353: state => state.app['TYPE0353'] // 专业层次
    }),
    zsnd () {
      return this.$route.query.zsnd
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        hideDefaultSelections: false,
        onChange: this.onSelectChange,
        // onSelect: (record, selected) => {
        //   this.xfChange(record, selected)
        // },
        // onSelectAll: selected => {
        //   this.planInfo.pyjh.jhbxkms = 0
        //   this.planInfo.pyjh.jhbxkxf = 0
        //   this.planInfo.pyjh.jhxxkms = 0
        //   this.planInfo.pyjh.jhxxkxf = 0
        //   this.planInfo.pyjh.jhxwkms = 0
        //   this.planInfo.pyjh.jhxwkxf = 0
        //   if (selected) {
        //     this.selectedRowKeys = this.planInfo.pyjhkcList.map((kc, index) => {
        //       this.xfChange(kc, true)
        //       return index
        //     })
        //   } else {
        //     this.selectedRowKeys = this.planInfo.pyjhkcList.filter((kc, index) => {
        //       return kc.sfmbkc === '1'
        //     }).map((kc, index) => {
        //       this.xfChange(kc, true)
        //       return index
        //     })
        //   }
        // },
        getCheckboxProps: record => ({
          props: {
            // 只能修改当前院系
            disabled: (this.currentUser.departmentId && record.zdzyssyxdm !== this.currentUser.departmentId)
          }
        })
      }
    }
  },
  components: {DetailList, DetailListItem},
  // watch: {
  //   systemInfo: {
  //     handler (val) {
  //       if (val && val.currentGrade) {
  //         this.getInfo()
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {
    this.$store.dispatch('app/setDictionary', 'TYPE0353')
    // this.$store.dispatch('app/sysInfo')
    this.getInfo()
    this.$store.dispatch('app/sysInfo', true).then(res => {
      this.tutorMasterAdmissionAgeLine = res.tutorMasterAdmissionAgeLine instanceof Object ? res.tutorMasterAdmissionAgeLine.format('YYYY-MM-DD') : res.tutorMasterAdmissionAgeLine
      this.tutorDoctoralAdmissionAgeLine = res.tutorDoctoralAdmissionAgeLine instanceof Object ? res.tutorDoctoralAdmissionAgeLine.format('YYYY-MM-DD') : res.tutorDoctoralAdmissionAgeLine
    })
    this.$api.teacher.teacherRecruitUnit({dsbh: this.$route.params.dsbh, zsnd: this.zsnd}).then(res => {
      this.selectMenu.yx = res.data
      if(res.data.length === 1){
        this.$nextTick(()=>{
          this.form.setFieldsValue({zdzyssyxdm: this.selectMenu.yx[0].yxm})
          this.yxChange(this.selectMenu.yx[0].yxm)
        })
      }
    })
    // this.$api.base.collegeAll().then(res => {
    //   this.selectMenu.yx = res.data
    //   if(res.data.length === 1){
    //     this.form.setFieldsValue({zdzyssyxdm: this.selectMenu.yx[0].dwh})
    //     this.yxChange(this.selectMenu.yx[0].dwh)
    //   }
    // })
    this.$api.teacher.teacherInfo({dsbh: this.$route.params.dsbh}).then(res => {
      this.teacherInfo = {...res.data, ...this.teacherInfo}
    })
  },
  methods: {
    getInfo () {
      this.$api.teacher.teacherZdzyInfo({dsbh: this.$route.params.dsbh, zsnd: this.zsnd}).then(res => {
        this.teacherInfo.dsxxId = res.data.id
        this.dszdzyList = res.data && res.data.dszdzyList
        this.dszdzyList.length && this.dszdzyList.forEach(async dszdzy => {
          let {data} = await this.$api.base.researchListByDistinct2({
            ssyxm: dszdzy.zdzyssyxdm,
            sszym: dszdzy.zdzym,
            zyccm: dszdzy.zyccm,
            zsxn: this.zsnd
          })
          let researchList = data.map(item => {
            return {
              value: item.yjfxm,
              label: item.yjfxm.substring(item.yjfxm.length - 2) +' - '+ item.yjfxmc
            }
          })
          this.$set(dszdzy, 'researchList', researchList)
          this.$set(dszdzy, 'dsyjfxList', dszdzy.dsyjfxList.map(fx => {
            return fx.yjfxm
          }))
        })
      })
    },
    yxChange (code) {
      this.form.setFieldsValue({zdzym: ''})
      let zycc = this.form.getFieldValue('zyccm')
      if (code && zycc) {
        let params = {lsdwh: code, zycc, zsnd: this.zsnd}
        // if (this.teacherInfo.dslbm === '1') {
        //   delete params.zycc
        // }
        this.$api.base.majorAll(params).then(res => {
        // this.$api.base.majorAll({lsdwh: code, zycc, dsxxId: this.teacherInfo.dsxxId, zsnd: this.zsnd}).then(res => {
          this.$set(this.selectMenu, 'zy', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'zy', [])
      }
    },
    zyccChange(code) {
      this.form.setFieldsValue({zdzym: ''})
      let lsdwh = this.form.getFieldValue('zdzyssyxdm')
      if (code && lsdwh) {
        let params = {lsdwh, zycc: code, zsnd: this.zsnd}
        // if (this.teacherInfo.dslbm === '1') {
        //   delete params.zycc
        // }
        this.$api.base.majorAll(params).then(res => {
        // this.$api.base.majorAll({lsdwh, zycc: code, dsxxId: this.teacherInfo.dsxxId, zsnd: this.zsnd}).then(res => {
          this.$set(this.selectMenu, 'zy', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'zy', [])
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    batchDelete () {
      this.dszdzyList = this.dszdzyList.filter(item => {
        return !this.selectedRows.includes(item)
      })
      this.selectedRows = []
      this.selectedRowKeys = []
    },
    addItem () {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          let dszdzy = {
            zdzyssyxdmc: this.selectMenu.yx.find(item => {
              return String(item.yxm) === String(values.zdzyssyxdm)
            }).dwmc,
            zdzymc: this.selectMenu.zy.find(item => {
              return String(item.zyh) === String(values.zdzym)
            }).zymc,
            zdzym: values.zdzym,
            zyccmc: this.TYPE0353.find(item => {
              return String(item.code) === String(values.zyccm)
            }).name,
            ...values
          }
          let dszdzyList = this.dszdzyList.map(item => {
            // let dszdzy = Object.assign({}, item)
            // delete dszdzy.researchList
            return JSON.stringify({
              zdzyssyxdmc: item.zdzyssyxdmc,
              zdzymc: item.zdzymc,
              zdzym: item.zdzym,
              zyccmc: item.zyccmc,
            })
          })
          if (!dszdzyList.includes(JSON.stringify({
            zdzyssyxdmc: dszdzy.zdzyssyxdmc,
            zdzymc: dszdzy.zdzymc,
            zdzym: dszdzy.zdzym,
            zyccmc: dszdzy.zyccmc,
          }))) {
            let {data} = await this.$api.base.researchListByDistinct2({
              ssyxm: dszdzy.zdzyssyxdm,
              sszym: dszdzy.zdzym,
              zyccm: dszdzy.zyccm,
              zsxn: this.zsnd
            })
            let researchList = data.map(item => {
              return {
                value: item.yjfxm,
                label: item.yjfxm.substring(item.yjfxm.length - 2) + ' - ' + item.yjfxmc
              }
            })
            dszdzy.researchList = researchList
            this.dszdzyList.push(dszdzy)
            console.log(this.dszdzyList)
          }
        }
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    save () {
      this.loadingBtn = true
      let params = {
        dszdzyList: this.dszdzyList.map(item => {
          return {
            ...item
          }
        }),
        dsbh: this.$route.params.dsbh,
        zsnd: this.zsnd
      }
      params.dszdzyList.forEach(zy => {
        delete zy.researchList
        zy.dsyjfxList = zy.dsyjfxList && zy.dsyjfxList.map(item => {
          return {
            yjfxm: item
          }
        })
      })
      this.$api.teacher.modifyTeacherZdxx(params).then(res => {
        this.$router.back()
        this.$message.success(res.msg)
      }).finally(() => {
        this.loadingBtn = false
      })
    },
    back () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.research-title{
  padding: 10px;
  background-color: #fafafa;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
  margin: 20px 0;
}
</style>
